package fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.StringUtil;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.util.LogUtils;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import app.ContactInfo;
import app.GroupChat;
import app.Main;
import application.AppApplication;
import custom.PinnedSectionListView;
import custom.kyletterfilter.KyLetterfilter;
import custom.kyletterfilter.OnLetterfilterListener;
import fragment.contact.ContactsAdapter;
import fragment.contact.ContactsModel;
import fragment.contact.ContactsPersenter;
import fragment.contact.ContactsSearchAdapter;
import interfaces.IReturnObject;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.EmployeeItemDBModel;
import model.SearchItemModel;

/**
 * Created by yanglei on 15/9/17.
 */
public class Contacts extends AppFragment implements View.OnClickListener {

    private ContactsPersenter persenter;

    PinnedSectionListView list = null;
    ContactsAdapter sadapter = null;
    KyLetterfilter kyLetterfilter = null;
    android.support.v4.app.FragmentManager fragmentManager;
    DialogFragment mMenuDialogFragment;

    LinearLayout searchLinear;
    EditText editTextSearch;
    ImageButton btnClose;

    LinearLayout shadeSearchLinear;
    ListView listViewSearch;

    Button menu_ok;
    //
    private boolean hasHeaderAndFooter = true;
    private boolean isFastScroll = false;
    private boolean addPadding = true;
    private boolean isShadowVisible = false;
    private boolean isEdit = false;
    private boolean IsMultiple = true;
    /**
     * 隐藏emplid的人员信息
     */
    public String HideEmplIDList = "";
    public List<String> hideEmplIDArray = null;

    private ArrayList<EmployeeItemDBModel> SelectedList = null;

    private List<EmployeeItemDBModel> ListData;

    @Override
    public boolean onBackPressed() {

        String deptID = persenter.getListDataDataPreviousByNet();

        LogUtils.e("Contacts onBackPressed:" + deptID);
        LogUtils.e("Contacts:" + AppApplication.getUser().EmplID);

        if (deptID!=null&&deptID.equalsIgnoreCase("0")) {
            setMainShowBack();
        }

        if (TextUtils.isEmpty(deptID)) {
            return false;
        } else {
            return true;
        }
    }

    private void setMainShowBack() {
        if (getActivity().getClass() == Main.class) {
            setBtnBackDisplay(false);
        }
    }

    public void setIsShowSearch(boolean isShow) {

        searchLinear.setVisibility(isShow ? View.VISIBLE : View.GONE);

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_contacts);
//        persenter = new ContactsPersenter(this);
        fragmentManager = getFragmentManager();

    }

    private List<MenuObject> getMenuObjects() {
        List<MenuObject> menuObjects = new ArrayList<>();

        MenuObject close = new MenuObject("关闭");
        close.setResource(R.mipmap.icn_close);

        MenuObject search = new MenuObject("搜索");
        search.setResource(R.mipmap.search);

        MenuObject add = new MenuObject("添加到通讯录");
        add.setResource(R.mipmap.search);


        menuObjects.add(close);
        menuObjects.add(search);
        menuObjects.add(add);
        return menuObjects;
    }

    //显示 隐藏 搜索层
    void setShadeSearch(boolean F) {
        if (F) {
            shadeSearchLinear.setVisibility(View.VISIBLE);
            btnClose.setVisibility(View.VISIBLE);

        } else {
            btnClose.setVisibility(View.INVISIBLE);
            shadeSearchLinear.setVisibility(View.GONE);
            editTextSearch.setText("");
            editTextSearch.setFocusableInTouchMode(false);
            editTextSearch.setFocusable(false);
            editTextSearch.setFocusable(true);
            editTextSearch.setFocusableInTouchMode(true);
            listViewSearch.setAdapter(null);
            IMEHelper.hideIME(getActivity(), true);

        }
    }

    @Override
    public void init() {
        super.init();
        initView();
        //是否是选择器

        ArrayList<EmployeeItemDBModel> DataList = initData();

        btnClose.setVisibility(View.INVISIBLE);
        shadeSearchLinear.setVisibility(View.GONE);
        list.setShadowVisible(isShadowVisible);
        initEvent();
//        initListHeaderAndFooter();//原来的所有人和群聊放入list的adapter可适配的部分
        hideContent();
        initMenu();
        persenter.initFirstListData(DataList);
    }

    /**
     * 初始化菜单
     */
    private void initMenu() {
        MenuParams menuParams = new MenuParams();
        menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
        menuParams.setMenuObjects(getMenuObjects());
        menuParams.setClosableOutside(false);
        mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
    }

    /**
     * 初始化数据 如获取到传入的list就返回 没有就返回null
     *
     * @return
     */
    private ArrayList<EmployeeItemDBModel> initData() {
        ArrayList<EmployeeItemDBModel> dataList = null;
        if (IsReturnResult) {
            searchLinear.setVisibility(View.GONE);
            try {
                IsMultiple = TagBundle.getBoolean("IsMultiple");
            } catch (Exception ex) {
            }
            try {
                HideEmplIDList = TagBundle.getString("HideEmplIDList");
                if (!StringUtil.isEmpty(HideEmplIDList)) {
                    hideEmplIDArray = java.util.Arrays.asList(HideEmplIDList.split(","));
                }
            } catch (Exception e) {
            }

            try {
                SelectedList = (ArrayList<EmployeeItemDBModel>) TagBundle.getSerializable("SelectedList");
                for (EmployeeItemDBModel model : SelectedList) {
                    model.checked = true;
                    LogUtils.e("传递来得数据：" + model.toString());
                    persenter.setSelectEmpl(model);
                }
            } catch (Exception ex) {
            }

            try {
                dataList = (ArrayList<EmployeeItemDBModel>) TagBundle.getSerializable("DataList");
            } catch (Exception ex) {
                dataList = null;
            }

            menu_ok.setVisibility(View.VISIBLE);
            setEdit(true);

        } else {
            menu_ok.setVisibility(View.GONE);
        }
        return dataList;
    }


    private void initView() {
        setCustomRightButton(R.layout.menu_contacts);
        menu_ok = (Button) getRootView().findViewById(R.id.menu_btn_ok);
        btnClose = (ImageButton) getRootView().findViewById(R.id.btnClose);
        shadeSearchLinear = (LinearLayout) getRootView().findViewById(R.id.shadeSearchLinear);
        searchLinear = (LinearLayout) getRootView().findViewById(R.id.searchLinear);
        editTextSearch = (EditText) getRootView().findViewById(R.id.editTextSearch);
        listViewSearch = (ListView) getRootView().findViewById(R.id.listViewSearch);
        kyLetterfilter = (KyLetterfilter) getRootView().findViewById(R.id.kyLetterfilter);
        list = (PinnedSectionListView) getRootView().findViewById(R.id.PinnedSectionList);
        ListData = new ArrayList<EmployeeItemDBModel>();
        sadapter = new ContactsAdapter(getActivity(), ListData, isEdit);

        list.setAdapter(sadapter);
        setIsShowSearch(false);
    }

    /**
     * 绑定事件
     */
    private void initEvent() {
        menu_ok.setOnClickListener(this);
        kyLetterfilter.setOnLetterfilterListener(new OnLetterfilterListener() {
            @Override
            public void start() {
            }

            @Override
            public void end() {
            }

            @Override
            public void letterChanged(String letter) {
                if (letter.equals("#")) {
                    list.setSelection(0);
                    return;
                }
                if (sadapter == null) {
                    return;
                }
                int index = -1;//下标
                for (int i = 0; i < sadapter.getAllData().size(); i++) {
                    EmployeeItemDBModel employeeItemDBModel = sadapter.getAllData().get(i);
                    String firstChar = employeeItemDBModel.Name.substring(0, 1);
                    firstChar = firstChar.toUpperCase();
                    if (firstChar.equals(letter)) {
                        index = i;
                        break;
                    }
                }
                if (index != -1)
                    list.setSelection(index);
            }
        });

        /**
         * firstVisibleItem : 当前能看见的第一个列表项position
         * visibleItemCount : 当前能看见的列表项个数（小半个也算）
         * totalItemCount : 列表项共数;
         */
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (sadapter == null) {
                    return;
                }
                if ((sadapter.getAllData().size() - 1) < firstVisibleItem)
                    return;
                EmployeeItemDBModel employeeItemDBModel = sadapter.getAllData().get(firstVisibleItem);
                String firstChar = employeeItemDBModel.Name.substring(0, 1);
                firstChar = firstChar.toUpperCase();
                kyLetterfilter.setCurrent(firstChar);
            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {

            }
        });

        editTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    IMEHelper.hideIME(getActivity(), true);
                    List<SearchItemModel> list = ContactsSearchAdapter.getSearchData(v.getText().toString(), sadapter.getAllData());
                    if (list != null) {
                        ContactsSearchAdapter adapter = new ContactsSearchAdapter(getActivity(), list);
                        listViewSearch.setAdapter(adapter);
                    } else {
                        showSimpleDialogMessage("没有搜索到任何信息", new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                setShadeSearch(false);
                            }
                        }, false, false);
                    }
                }
                return false;
            }
        });
        editTextSearch.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setShadeSearch(true);
                return false;
            }
        });

        btnClose.setOnClickListener(this);
        shadeSearchLinear.setOnClickListener(this);
        listViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SearchItemModel item = (SearchItemModel) parent.getAdapter().getItem(position);
                Intent it = new Intent(context, ContactInfo.class);
                it.putExtra("emplID", item.ID);
                startActivity(it);
            }
        });

        list.setOnScrollListener(new PauseOnScrollListener(getBitmapLoader(), true, true));
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //如果id是-1说明这个是Header 或者  Footer
                if (id == -1) {
                    //判断header 和   footer
                    int i = view.getId();
                    if (i == R.id.header_session_group) {//startActivity(new Intent(context,SessionGroupActivity.class));

                    } else if (i == R.id.header_department) {
//                        Intent it = new Intent(context, AddressBookDeptSelector.class);
//                        it.putExtra("deptID", "0");
//                        it.putExtra("title", "部门");
//                        startActivity(it);
                        persenter.getListDeptDataByNet("all", true);
                        setBtnBackDisplay(true);
                    } else if (i == R.id.header_group_chat) {
                        Intent it = new Intent(context, GroupChat.class);
                        startActivity(it);
                    } else if (i == R.id.footer1) {
//                        MessageUtil.showShortToast(context, "footer1");
                    }
                } else {

                    EmployeeItemDBModel item = (EmployeeItemDBModel) parent.getAdapter().getItem(position);
                    if (TextUtils.isEmpty(item.EmplID) && TextUtils.isEmpty(item.DeptID)) {
                        LogUtils.e("no EmplID and no DeptID");
                    } else {

                        //如果是选择模式 并且是人员，则设置选中与不选中
                        if (isEdit && !TextUtils.isEmpty(item.EmplID)) {
                            if (item.type == EmployeeItemDBModel.ITEM) {
                                if (!IsMultiple) {
                                    sadapter.clearSelected();
                                    sadapter.notifyDataSetChanged();
                                }
                                item.checked = !item.checked;
                                if (item.checked) {
                                    ((ImageView) view.findViewById(R.id.imageViewCheck)).setImageResource(R.drawable.selecter_selected_icon);
                                } else {
                                    ((ImageView) view.findViewById(R.id.imageViewCheck)).setImageResource(R.drawable.selecter_unselected_icon);
                                }
                                persenter.setSelectEmpl(item);
                            }

                        } else {
                            //判断点击的是标题头还是真正的选项
                            if (item.type == EmployeeItemDBModel.ITEM) {
                                if (!TextUtils.isEmpty(item.DeptID)) {
                                    if (item.DeptID.equalsIgnoreCase("chat")) {
                                        Intent it = new Intent(context, GroupChat.class);
                                        startActivity(it);
                                    } else {
                                        setBtnBackDisplay(true);
                                        persenter.getListDeptDataByNet(item.DeptID, true);
                                        if (item.DeptID.equalsIgnoreCase("all")){
                                            setIsShowSearch(true);
                                        }
                                    }
                                } else if (!TextUtils.isEmpty(item.EmplID)) {
                                    Intent it = new Intent(context, ContactInfo.class);
                                    it.putExtra("emplID", item.EmplID);
                                    startActivity(it);
                                } else {

                                }
                            }
                        }
                    }
                }

            }
        });
    }

    public void setEdit(boolean F) {
        this.isEdit = F;
        sadapter.setEdit(this.isEdit);
        if (this.sadapter != null) {
            if (!F) {
                this.sadapter.clearSelected();
            }
            this.sadapter.notifyDataSetChanged();
        }
    }


    public List<EmployeeItemDBModel> getSelectData() {
        //return this.sadapter.getSelectData();
        return persenter.getCheckList();
    }

    public List<EmployeeItemDBModel> getAllData() {
        return this.sadapter.getAllData();
    }

    /**
     * 初始化主列表的 头View
     * 群聊 和 部门
     */
    private void initListHeaderAndFooter() {
        if (hasHeaderAndFooter) {
            View header1 = inflater.inflate(R.layout.adapter_item_group_chat, list, false);
            ImageView header1_img = (ImageView) header1.findViewById(R.id.imageView1);
            header1_img.setImageResource(R.mipmap.im_icon_se);
            TextView header1_text = (TextView) header1.findViewById(R.id.textView1);
            header1_text.setText("群聊");

            View header2 = inflater.inflate(R.layout.adapter_item_address_book_big, list, false);
            ImageView header2_img = (ImageView) header2.findViewById(R.id.imageView1);
            header2_img.setImageResource(R.mipmap.department_img);
            TextView header2_text = (TextView) header2.findViewById(R.id.textView1);
            header2_text.setText("所有人");
//            if(!IsReturnResult){
            list.addHeaderView(header1);
            list.addHeaderView(header2);
//            }

        }
    }

    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.menu_btn_ok) {//showMenu();
            ArrayList<EmployeeItemDBModel> list = null;
            try {
                list = (ArrayList<EmployeeItemDBModel>) getSelectData();
            } catch (Exception ex) {
                list = null;
            }
            //if (list != null) {
            Intent it = new Intent();
            it.putExtra("Data", list);
            it.putExtra("IsMultiple", IsMultiple);

            getAppActivity().setResult(Activity.RESULT_OK, it);
            // getAppActivity().onBackPressed();
            getActivity().finish();
            // } else {
            //      MessageUtil.showShortToast(context, "请选择");
            // }


        } else if (i == R.id.btnClose) {
            setShadeSearch(false);
        } else if (i == R.id.shadeSearchLinear) {
            setShadeSearch(false);
        }
    }


    public void setAdapterNotifyDataSetChanged(List<EmployeeItemDBModel> listData) {
        ListData.clear();
        ListData.addAll(listData);
        sadapter.notifyDataSetChanged();
        list.setFastScrollEnabled(isFastScroll);
        if (isFastScroll) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                list.setFastScrollAlwaysVisible(true);
            }
        }
//      if(footer!=null){
//          footer.setText("{0}位联系人".replace("{0}", sadapter.getItemTypeCount()+""));
//      }
        showContent();
        hideAll(500);
    }
}
